package com.example.demo.config;

import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * *****************************************************************
 * <p>
 * RestTemplate配置类<br/>
 *
 * @className: RestTemplateConfig.java
 * @author: zfw2660
 * @date: 2018/9/18 09:01
 * @version: 1.0
 * <p>
 * *****************************************************************
 **/
@Configuration
@ConditionalOnClass(value = {RestTemplate.class, HttpClient.class})
public class RestTemplateConfig {
    /**
     * 连接池的最大连接数
     */
    @Value("${rest.rest-template.max_total_connect}")
    private int maxTotalConnect;
    /**
     * 单个主机的最大连接数
     */
    @Value("${rest.rest-template.max_connect_per_route}")
    private int maxConnectPerRoute;
    /**
     *连接超时（单位ms）
     */
    @Value("${rest.rest-template.connect-timeout}")
    private int connectTimeout;
    /**
     * 读取超时（单位ms）
     */
    @Value("${rest.rest-template.read-timeout}")
    private int readTimeout;

    /**
     *
     * 创建HTTP客户端工厂<br/>
     *
     * @return  org.springframework.http.client.ClientHttpRequestFactory
     * @author  zfw2660
     * @date    2018/9/18 9:22
     * @other
     * @exception
     *
     */
    private ClientHttpRequestFactory createFactory() {
        if (this.maxTotalConnect <= 0) {
            SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
            factory.setConnectTimeout(this.connectTimeout);
            factory.setReadTimeout(this.readTimeout);
            return factory;
        }
        HttpClient httpClient = HttpClientBuilder.create()
                .useSystemProperties()
                .setMaxConnTotal(this.maxTotalConnect)
                .setMaxConnPerRoute(this.maxConnectPerRoute).build();
        HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(
                httpClient);
        factory.setConnectTimeout(this.connectTimeout);
        factory.setReadTimeout(this.readTimeout);
        return factory;
    }

    /**
     *
     * 初始化RestTemplate,并加入spring的Bean工厂，由spring统一管理<br/>
     *
     * @return  org.springframework.web.client.RestTemplate
     * @author  zfw2660
     * @date    2018/9/18 9:12
     * @other
     * @exception
     *
     */
    @Bean
    @ConditionalOnMissingBean(RestTemplate.class)
    public RestTemplate getRestTemplate() {
        RestTemplate restTemplate = new RestTemplate(this.createFactory());
        List<HttpMessageConverter<?>> converterList = restTemplate.getMessageConverters();

        //重新设置StringHttpMessageConverter字符集为UTF-8，解决中文乱码问题
        HttpMessageConverter<?> converterTarget = null;
        for (HttpMessageConverter<?> item : converterList) {
            if (StringHttpMessageConverter.class == item.getClass()) {
                converterTarget = item;
                break;
            }
        }
        if (null != converterTarget) {
            converterList.remove(converterTarget);
        }
        converterList.add(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));

        //加入FastJson转换器 根据使用情况进行操作，此段注释，默认使用jackson
        //converterList.add(new FastJsonHttpMessageConverter4());
        return restTemplate;
    }
}
